<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./框架相关的js/xlsx.js"></script>
</head>

<body>

  <input type="file" id="fileUploader" name="fileUploader" accept=".xls, .xlsx" />
  <table border style="display:none">
    <tr>
      <th>姓名</th>
      <th>年龄</th>
      <th>入职日期</th>
      <th>爱好</th>
    </tr>
  </table>
  <script>

    var fileUploader = document.getElementById('fileUploader')
    fileUploader.onchange = function (e) {
      var files = e.target.files;
      var reader = new FileReader();
      reader.readAsBinaryString(files[0])
      reader.onload = function (event) {
        // 文件里的文本会在这里被打印出来
        try {
          const data = event.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          var wsname = workbook.SheetNames[0]
          var wx = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
          if (workbook.Sheets.Sheet1.A1.h != '姓名') {
            alert('请导入正确的模板')
            return
          }
          let arr = []
          //    将表格的文字装换为对应的字段
          wx.forEach(item => {
            console.log(item, 'item');
            let obj = {}
            // 导入的excel模板表头例子：
            // obj.name=item['姓名']
            // obj.number=item['序号']
            // obj.constellation=item['星座']
            // obj.place=item['来自哪里']
            // obj.nation=item['民族']
            // obj.department=item['部门']
            obj.name = item['姓名']?item['姓名']:''
            obj.age = item['年龄']?item['年龄']:''
            obj.date = item['入职日期']?item['入职日期']:''
            obj.hobby = item['爱好']?item['爱好']:''
            arr.push(obj)
          })

          console.log(arr, '表格转成数据格式');
          var table1 = document.querySelector('table')
          table1.style.display = 'inline-block'
          arr.forEach(item => {
            table1.innerHTML += `
           <tr>
            <td> ${item.name}</td>
            <td> ${item.age}</td>
            <td> ${item.date}</td>
            <td> ${item.hobby}</td>
            </tr>
        `
          })

        }
        catch (e) {
          console.log(e, '捕获到的错误信息');
        }
      };
      //   reader.readAsText(file);
    }


  </script>
</body>

</html>